/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

package edu.ucla.cs.typecast.rmi.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import edu.ucla.cs.typecast.bloomfilter.BloomFilter;
import edu.ucla.cs.typecast.bloomfilter.BloomFilterEncoder;
import edu.ucla.cs.typecast.net.EndPoint;
import edu.ucla.cs.typecast.net.TransportContext;
import edu.ucla.cs.typecast.net.TransportSender;
import edu.ucla.cs.typecast.net.TransportSenderFactory;
import edu.ucla.cs.typecast.net.TypeCastDispatcher;
import edu.ucla.cs.typecast.rmi.Future;
import edu.ucla.cs.typecast.rmi.InvocationMarshaller;
import edu.ucla.cs.typecast.rmi.InvocationUnmarshaller;
import edu.ucla.cs.typecast.rmi.MethodInvocation;
import edu.ucla.cs.typecast.rmi.runtime.RMIReturnValueProcessor;
import edu.ucla.cs.typecast.rmi.runtime.RMIUtil;
import edu.ucla.cs.typecast.util.TypeUtil;

/**
 * 
 * This class unmarshalls the incoming network packets into a TypeCast 
 * method invocation. 
 * 
 * @date Jul 25, 2007
 *
 */
public class TypeCastMethodInvocationDispatcher implements TypeCastDispatcher {
	private EndPoint endPoint; 
	public TypeCastMethodInvocationDispatcher(EndPoint endPoint) { 
		this.endPoint = endPoint; 
	}
	public void dispatch(TransportContext transportContext, InputStream inputStream) throws IOException { 
		InvocationUnmarshaller unmarshaller = new InvocationUnmarshaller(); 
		MethodInvocation invocation = unmarshaller.unmarshall(inputStream); 
		Collection services; 
		if (invocation.isMeta()) { 
			Object service = TypeCastObjectManager.getInstance().getMetaServiceObject(invocation.getMethod().getDeclaringClass()); 
			services = new ArrayList(1); 
			services.add(service); 
		} else { 
			TypeCastServiceRegistrar registrar = TypeCastObjectManager.getInstance().getServiceRegistrar(endPoint); 
			services = registrar.getServices(invocation); 
		}
		if (services != null && services.size() > 0) { 
			for(Object service : services) {
				try { 
					Object result = invocation.getMethod().invoke(service, invocation.getArguments()); 
					if (invocation.getCorrelationID() != null) { 
						sendResult(transportContext.getSource(), invocation, result); 
					}
				} catch(Throwable t) { 
					t.printStackTrace(); 
				}
			}
		}		
	}
	
	private void sendResult(EndPoint source, MethodInvocation invocation, Object result) throws IOException, NoSuchMethodException  { 
		Future future = (Future)result; 
		if (future == null || future.getCounts() <= 0) { 
			return; 
		}
		
		ByteArrayOutputStream bas = new ByteArrayOutputStream();
		InvocationMarshaller marshaller = new InvocationMarshaller(); 		
		Method processMethod = RMIUtil.getMethodForProcessReturnValue(); 
		Object[] args = new Object[] { invocation.getCorrelationID(), future.get(0) }; 
		MethodInvocation sendResult = new MethodInvocation(new Class[] { RMIReturnValueProcessor.class }, processMethod, args); 
		marshaller.marshall(bas, sendResult); 		
		BloomFilter filter = BloomFilterEncoder.encode(TypeUtil.getAllTypes(new Class[] {RMIReturnValueProcessor.class } )); 
		TransportSender transportSender = TransportSenderFactory.createTransportSender(source); 
		transportSender.send(filter, bas.toByteArray(), 0, bas.size()); 

	}
}
